package com.purchase.ml.resource.order;

import com.purchase.ml.annotations.OperLog;
import com.purchase.ml.bean.base.ApiRestResult;
import com.purchase.ml.bean.req.log.OperationLogQueryDto;
import com.purchase.ml.bean.req.order.*;
import com.purchase.ml.bean.req.shoppingcart.ProductCartReq;
import com.purchase.ml.bean.res.shoppingcart.ShoppingCartRes;
import com.purchase.ml.consts.CommonConsts;
import com.purchase.ml.consts.PermissionsConst;
import com.purchase.ml.entity.acc.SysUser;
import com.purchase.ml.entity.dealer.SysDealer;
import com.purchase.ml.entity.dealer.SysDealerPruduct;
import com.purchase.ml.entity.prod.SysProductSku;
import com.purchase.ml.enums.ManagerStatusEnum;
import com.purchase.ml.enums.RetStatusNum;
import com.purchase.ml.mapper.dealer.DealerProductMapper;
import com.purchase.ml.resource.BaseResource;
import com.purchase.ml.security.JwtUtil;
import com.purchase.ml.service.dealer.SysDealerService;
import com.purchase.ml.service.log.OperationLogService;
import com.purchase.ml.service.order.SysOrderService;
import com.purchase.ml.service.prod.DealerProductService;
import com.purchase.ml.service.prod.SysProdService;
import com.purchase.ml.service.prod.SysProdSkuService;
import com.purchase.ml.service.shoppingcart.SysShoppingCartService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import static com.purchase.ml.consts.CommonConsts.ROLETYPE_DEALER;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author kyyang
 * Created 2021-02-28
 */

@RestController
@RequestMapping("/order")
@Api(tags = "订单购物车")
@Slf4j
public class OrderResource extends BaseResource {

    @Autowired
    private SysShoppingCartService sysShoppingCartService;

    @Autowired
    private SysProdSkuService sysProdSkuService;

    @Autowired
    private SysOrderService sysOrderService;
    @Autowired
    private DealerProductMapper dealerProductMapper;
    @Autowired
    private SysDealerService sysDealerService;



    @RequestMapping(method = RequestMethod.POST, path = "/addtocart")
    @ApiOperation("添加商品到购物车")
    @RequiresPermissions(PermissionsConst.SHOP_ORDERCART_ADD)
    @OperLog(operDesc = "AddToCart", operModul = "Cart", operType = "Add")
    public ApiRestResult add2Cart(@RequestBody @Valid ProductCartReq productCartReq) {
        //校验商品数量
        if(productCartReq.getQuantity()<=0){
            log.error("添加商品到购物车,数量为:[{}]",productCartReq.getQuantity());
            return ApiRestResult.err("Kuantiti tidak boleh kurang daripada 0", RetStatusNum.PARAMS_ERROR.getCode());
        }
        //校验库存数
        SysProductSku sysProductSku = sysProdSkuService.findProductSkuByProductId(productCartReq.getProductId());
        SysUser currentUser = JwtUtil.getCurrentUser();
        if(Integer.valueOf(ROLETYPE_DEALER).equals(currentUser.getRoleType())){
            SysDealer currentDealer = sysDealerService.findByDealerId(currentUser.getDealerId());
            SysDealerPruduct sysDealerPruduct = dealerProductMapper.findBuyerProductByDealerId(currentDealer.getSuperior(), productCartReq.getProductId());
            BeanUtils.copyProperties(sysDealerPruduct,sysProductSku);
            log.info("当前商品sku为[{}]",sysProductSku);
        }
        if(sysProductSku==null||sysProductSku.getStock()<productCartReq.getQuantity()){
            return ApiRestResult.err("Stok kurang! Hanya "+(sysProductSku==null?0:sysProductSku.getStock()) +" yang tinggal", RetStatusNum.PARAMS_ERROR.getCode());
        }
        sysShoppingCartService.addProduct2Cart(productCartReq);
        return ApiRestResult.ok();
    }


    @RequestMapping(method = RequestMethod.POST, path = "/editcart")
    @ApiOperation("修改购物车商品数量")
    @RequiresPermissions(PermissionsConst.SHOP_ORDERCART_EDIT)
    @OperLog(operDesc = "EditCartProduct", operModul = "Cart", operType = "Edit")
    public ApiRestResult editProduct2Cart(@RequestBody @Valid ProductCartReq productCartReq) {
        //校验商品数量
        if(productCartReq.getQuantity()<0){
            log.error("添加商品到购物车,数量为:[{}]",productCartReq.getQuantity());
            return ApiRestResult.err("Kuantiti tidak boleh kurang daripada 0", RetStatusNum.PARAMS_ERROR.getCode());
        }
        //校验库存数
        SysProductSku sysProductSku = sysProdSkuService.findProductSkuByProductId(productCartReq.getProductId());
        SysUser currentUser = JwtUtil.getCurrentUser();
        if(Integer.valueOf(ROLETYPE_DEALER).equals(currentUser.getRoleType())){
            SysDealer currentDealer = sysDealerService.findByDealerId(currentUser.getDealerId());
            SysDealerPruduct sysDealerPruduct = dealerProductMapper.findBuyerProductByDealerId(currentDealer.getSuperior(), productCartReq.getProductId());
            BeanUtils.copyProperties(sysDealerPruduct,sysProductSku);
        }
        if(sysProductSku==null||sysProductSku.getStock() < productCartReq.getQuantity()){
            return ApiRestResult.err("Stok kurang ! Hanya"+(sysProductSku==null?0:sysProductSku.getStock()) +" yang tinggal", RetStatusNum.PARAMS_ERROR.getCode());
        }
        sysShoppingCartService.modifyProduct2Cart(productCartReq);
        return ApiRestResult.ok();
    }


    @RequestMapping(method = RequestMethod.POST, path = "/clearcart")
    @ApiOperation("清空购物车")
    @RequiresPermissions(PermissionsConst.SHOP_ORDERCART_EDIT)
    @OperLog(operDesc = "ClearCartProduct", operModul = "Cart", operType = "Clear")
    public ApiRestResult clearProduct2Cart() {
        sysShoppingCartService.clearCart();
        return ApiRestResult.ok();
    }


    @RequestMapping(method = RequestMethod.POST, path = "/delcart")
    @ApiOperation("删除购物车商品")
    @RequiresPermissions(PermissionsConst.SHOP_ORDERCART_EDIT)
    @OperLog(operDesc = "DelCartProduct", operModul = "Cart", operType = "Delete")
    public ApiRestResult delProduct2Cart(@RequestBody @Valid ProductCartReq productCartReq) {
        sysShoppingCartService.delProduct2Cart(productCartReq);
        return ApiRestResult.ok();
    }


    @RequestMapping(method = RequestMethod.POST, path = "/querycart")
    @ApiOperation("查询购物车")
    @RequiresPermissions(PermissionsConst.SHOP_ORDERCART_QUERY)
    public ApiRestResult queryCurCart() {
        List<ShoppingCartRes> productCartReqs = sysShoppingCartService.queryProduct2Cart();
        return ApiRestResult.ok(productCartReqs);
    }

    @RequestMapping(method = RequestMethod.POST, path = "/new")
    @ApiOperation("创建订单")
    @RequiresPermissions(PermissionsConst.SHOP_ORDER_NEW)
    @OperLog(operDesc = "OrderCreate", operModul = "Order", operType = "Create")
    public ApiRestResult orderCreate(@RequestBody @Valid OrderAddReq req) throws NoSuchAlgorithmException {
        ApiRestResult backDate = sysOrderService.orderCreate(req);
        return backDate  ;
    }

    @RequestMapping(method = RequestMethod.POST, path = "/admin_add")
    @ApiOperation("管理员添加订单")
    @RequiresPermissions(PermissionsConst.SHOP_ORDER_NEW)
    @OperLog(operDesc = "OrderCreateAdmin", operModul = "Order", operType = "AdminCreate")
    public ApiRestResult orderAdminAdd(@RequestBody @Valid OrderAdminAddReq req) throws NoSuchAlgorithmException {
        return sysOrderService.orderAdminCreate(req);
    }
    @RequestMapping(method = RequestMethod.POST, path = "/edit")
    @ApiOperation("修改订单状态")
    @RequiresPermissions(PermissionsConst.ORDER_EDIT)
    @OperLog(operDesc = "OrderEdit", operModul = "Order", operType = "Edit")
    public ApiRestResult orderEdit(@RequestBody @Valid OrderEditReq orderEditReq) {
        return sysOrderService.orderEdit(orderEditReq);
    }

    @RequestMapping(method = RequestMethod.POST, path = "/del")
    @ApiOperation("删除订单")
    @RequiresPermissions(PermissionsConst.ORDER_EDIT)
    @OperLog(operDesc = "OrderDel", operModul = "Order", operType = "Delete")
    public ApiRestResult orderDel(@RequestBody @Valid List<Long> oids) {

        return sysOrderService.orderDel(oids);
    }


    @RequestMapping(method = RequestMethod.POST, path = "/query")
    @ApiOperation("采购订单查询")
    @RequiresPermissions(PermissionsConst.ORDER_QUERY)
    public ApiRestResult orderQuery(@RequestBody @Valid OrderQueryReq orderQueryReq) {
        return ApiRestResult.ok(sysOrderService.orderQuery(orderQueryReq,false));
    }

    @RequestMapping(method = RequestMethod.POST, path = "/query/myorder")
    @ApiOperation("我的订单查询")
    @RequiresPermissions(PermissionsConst.ORDER_QUERY)
    public ApiRestResult myOrderQuery(@RequestBody @Valid OrderQueryReq orderQueryReq) {
        return ApiRestResult.ok(sysOrderService.orderQuery(orderQueryReq,true));
    }

    @RequestMapping(method = RequestMethod.POST, path = "/queryinfo")
    @ApiOperation("通过单号查询订单详情")
    @RequiresPermissions(PermissionsConst.ORDER_QUERY)
    public ApiRestResult orderQueryInfo(@RequestBody @Valid OrderQueryInfoReq orderQueryInfoReq) {
        return ApiRestResult.ok(sysOrderService.orderQueryInfo(orderQueryInfoReq,false));
    }

    @RequestMapping(method = RequestMethod.POST, path = "/query/myorder/info")
    @ApiOperation("通过单号查询我的订单详情")
    @RequiresPermissions(PermissionsConst.ORDER_QUERY)
    public ApiRestResult myOrderQueryInfo(@RequestBody @Valid OrderQueryInfoReq orderQueryInfoReq) {
        return ApiRestResult.ok(sysOrderService.orderQueryInfo(orderQueryInfoReq,true));
    }


    @RequestMapping(method = RequestMethod.POST, path = "/invoice/query")
    @ApiOperation("查询所有订单的发票")
    @RequiresPermissions(PermissionsConst.INVOICE_QUERY)
    public ApiRestResult orderInvoiceQuery(@RequestBody @Valid OrderInvoiceQueryReq orderInvoiceQueryReq) {
        return ApiRestResult.ok(sysOrderService.orderInvoiceQuery(orderInvoiceQueryReq));
    }

    @RequestMapping(method = RequestMethod.POST, path = "/invoice/queryinfo")
    @ApiOperation("通过单号查询发票详情")
    @RequiresPermissions(PermissionsConst.INVOICE_QUERY)
    public ApiRestResult orderInvoiceQueryInfo(@RequestBody @Valid OrderInvoiceQueryInfoReq orderInvoiceQueryInfoReq) {
        return ApiRestResult.ok(sysOrderService.orderInvoiceQueryInfo(orderInvoiceQueryInfoReq));
    }

}